<?php
/**
 * WordPress Spider Monitor - 安全许可证验证模块
 * 
 * 此模块提供服务器端验证，防止客户端绕过授权
 * 所有关键功能必须通过远程服务器验证
 */

if (!defined('ABSPATH')) {
    exit;
}

class WP_Spider_Secure_License_Verification {
    
    private static $instance = null;
    private $license_server_url = 'https://zibovip.top/dingyue/license-api.php'; // 您的许可证服务器
    private $cache_duration = 300; // 5分钟缓存
    
    /**
     * 获取单例实例
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 构造函数
     */
    private function __construct() {
        // 初始化
    }
    
    /**
     * 验证许可证（统一验证逻辑）
     */
    public function verify_license($license_key = null) {
        // 暂时全部免费：直接返回激活状态
        return $this->create_verification_result(true, '许可证验证成功', array(
            'status' => 'active',
            'features' => array('all'),
            'periods' => array('today', 'yesterday', 'week', 'month'),
            'expires_at' => null,
            'domain' => $this->get_current_domain()
        ));
    }
    
    /**
     * 远程验证许可证
     */
    private function remote_verify_license($license_key) {
        $domain = $this->get_current_domain();
        $user_id = get_current_user_id();
        
        $request_data = array(
            'license_key' => $license_key,
            'domain' => $domain,
            'user_id' => $user_id,
            'plugin_version' => '1.0.0',
            'timestamp' => time(),
            'signature' => $this->generate_request_signature($license_key, $domain, $user_id)
        );
        
        $response = wp_remote_post($this->license_server_url . '?action=verify', array(
            'body' => $request_data,
            'headers' => array(
                'Content-Type' => 'application/x-www-form-urlencoded',
                'User-Agent' => 'WP-Spider-Monitor/1.0.0'
            ),
            'timeout' => 10,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) {
            return $this->create_verification_result(false, '网络连接失败');
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return $this->create_verification_result(false, '服务器响应错误');
        }
        
        $response_body = wp_remote_retrieve_body($response);
        $result = json_decode($response_body, true);
        
        if (!$result) {
            return $this->create_verification_result(false, '服务器响应格式错误');
        }
        
        // 验证服务器签名（暂时跳过，因为当前API没有签名验证）
        // if (!$this->verify_server_signature($result)) {
        //     return $this->create_verification_result(false, '服务器签名验证失败');
        // }
        
        // 检查许可证是否成功且状态为active
        $is_valid = $result['success'] === true && ($result['status'] ?? '') === 'active';
        
        // 提供更详细的错误信息
        $message = '许可证验证失败';
        if ($result['success'] === true) {
            $status = $result['status'] ?? 'unknown';
            switch ($status) {
                case 'active':
                    $message = '许可证验证成功';
                    break;
                case 'inactive':
                    $message = '许可证未激活，请先激活许可证';
                    break;
                case 'expired':
                    $message = '许可证已过期';
                    break;
                case 'invalid':
                    $message = '许可证无效';
                    break;
                default:
                    $message = '许可证状态未知: ' . $status;
            }
        } else {
            $message = $result['message'] ?? '许可证验证失败';
        }
        
        return $this->create_verification_result(
            $is_valid,
            $message,
            $result
        );
    }
    
    /**
     * 令牌校验的功能访问验证（本地）
     * 轻量混淆：变量名+简单哈希校验
     */
    public function verify_feature_access($feature, $period = 'today', $license_key = null, $token = null) {
        // 暂时全部免费：直接放行
        return array('success' => true, 'is_premium' => true, 'data' => array());
    }

    /**
     * 校验令牌（结构：base64(json:{t,exp,feat,per,chk,sign}))
     */
    private function validate_token($token, $feature, $period, $marker) {
        $raw = base64_decode($token, true);
        if ($raw === false) { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Token base64 decode failed');
            }
            return false; 
        }
        $obj = json_decode($raw, true);
        if (!is_array($obj)) { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Token JSON decode failed');
            }
            return false; 
        }
        // 基本字段
        if (empty($obj['t']) || empty($obj['exp']) || empty($obj['feat']) || empty($obj['per']) || empty($obj['sign'])) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Token missing required fields: ' . json_encode($obj));
            }
            return false;
        }
        if ($obj['feat'] !== $feature) { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Feature mismatch: expected ' . $feature . ', got ' . $obj['feat']);
            }
            return false; 
        }
        // per 可为 general 或具体周期，与 remote-auth.php 保持一致
        if (!in_array($obj['per'], array($period, 'general'), true)) { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Period mismatch: expected ' . $period . ' or general, got ' . $obj['per']);
            }
            return false; 
        }
        if ($obj['exp'] < time()) { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Token expired: exp=' . $obj['exp'] . ', now=' . time());
            }
            return false; 
        }
        // 仅接受 RS256 验签，拒绝其他算法，防止本地伪造
        if (empty($obj['alg']) || $obj['alg'] !== 'RS256') { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Algorithm mismatch: expected RS256, got ' . ($obj['alg'] ?? 'empty'));
            }
            return false; 
        }
        $pub = get_option('spider_server_public_key');
        if (!$pub) {
            // 尝试自动获取并保存服务端公钥，避免首次缺失导致验证失败
            try {
                $response = wp_remote_get('https://zibovip.top/dingyue/get-public-key.php', [ 'timeout' => 10, 'sslverify' => true ]);
                if (!is_wp_error($response)) {
                    $body = wp_remote_retrieve_body($response);
                    $data = json_decode($body, true);
                    if (is_array($data) && !empty($data['public_key'])) {
                        update_option('spider_server_public_key', $data['public_key']);
                        set_transient('spider_server_public_key', $data['public_key'], 3600);
                        $pub = $data['public_key'];
                    }
                }
            } catch (\Throwable $e) {
                // 忽略异常，保持原有失败逻辑
            }
        }
        if (!$pub) { 
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] No public key found');
            }
            return false; 
        }
        $payload = $obj['t'] . '|' . $obj['exp'] . '|' . $obj['feat'] . '|' . $obj['per'] . '|' . $marker;
        $sig = base64_decode($obj['sign']);
        $verify_result = function_exists('openssl_verify') ? openssl_verify($payload, $sig, $pub, OPENSSL_ALGO_SHA256) : false;
        if ($verify_result !== 1) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[SpiderAuth] Signature verification failed: result=' . $verify_result . ', payload=' . $payload . ', marker=' . $marker);
            }
        }
        return $verify_result === 1;
    }
    
    /**
     * 生成请求签名
     */
    private function generate_request_signature($license_key, $domain, $user_id) {
        $data = $license_key . $domain . $user_id . time();
        return hash_hmac('sha256', $data, $this->get_client_secret());
    }
    
    /**
     * 验证服务器签名
     */
    private function verify_server_signature($response) {
        if (!isset($response['signature'])) {
            return false;
        }
        
        $expected_signature = hash_hmac('sha256', 
            json_encode($response['data']), 
            $this->get_client_secret()
        );
        
        return hash_equals($expected_signature, $response['signature']);
    }
    
    /**
     * 获取客户端密钥
     */
    private function get_client_secret() {
        $secret = get_option('wp_spider_client_secret');
        if (!$secret) {
            $secret = wp_generate_password(64, true, true);
            update_option('wp_spider_client_secret', $secret);
        }
        return $secret;
    }
    
    /**
     * 创建验证结果
     */
    private function create_verification_result($valid, $message, $data = array()) {
        return array(
            'valid' => $valid,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        );
    }
    
    /**
     * 获取当前域名
     */
    private function get_current_domain() {
        return parse_url(home_url(), PHP_URL_HOST);
    }
    
    /**
     * 清除验证缓存
     */
    public function clear_verification_cache() {
        $license_key = get_option('wp_spider_license_key');
        if ($license_key) {
            $cache_key = 'wp_spider_license_verification_' . md5($license_key);
            delete_transient($cache_key);
        }
    }
    
    /**
     * 设置许可证密钥
     */
    public function set_license_key($license_key) {
        update_option('wp_spider_license_key', $license_key);
        $this->clear_verification_cache();
    }
    
    /**
     * 获取许可证信息
     */
    public function get_license_info() {
        $verification = $this->verify_license();
        
        return array(
            'is_active' => $verification['valid'],
            'message' => $verification['message'],
            'features' => $verification['data']['features'] ?? array(),
            'periods' => $verification['data']['periods'] ?? array('today', 'yesterday'),
            'expires_at' => $verification['data']['expires_at'] ?? null,
            'domain' => $this->get_current_domain()
        );
    }
}

/**
 * 获取安全许可证验证实例
 */
function wp_spider_secure_license_verification() {
    return WP_Spider_Secure_License_Verification::get_instance();
}

/**
 * 验证功能访问权限的便捷函数
 */
function wp_spider_verify_feature_access($feature, $period = 'today') {
    $verification = wp_spider_secure_license_verification();
    return $verification->verify_feature_access($feature, $period);
}
